<?php
namespace app\admin\controller;

// 引入框架内置类
use think\facade\Request;
use think\facade\Db;
// 引入表格和表单构建器
use app\common\facade\MakeBuilder;
use app\common\builder\FormBuilder;
use app\common\builder\TableBuilder;

class ProjectsSku extends Base
{
    // 验证器
    protected $validate = 'ProjectsSku';

    // 当前主表
    protected $tableName = 'projects_sku';

    // 当前主模型
    protected $modelName = 'ProjectsSku';

    // 列表
    public function index(){
        $projectsId = request()->get('projectsId');
        // 获取主键
        $pk = MakeBuilder::getPrimarykey($this->tableName);
        // 获取列表数据
        $coloumns = MakeBuilder::getListColumns($this->tableName);
        // 获取搜索数据
        $search = MakeBuilder::getListSearch($this->tableName);
        // 获取当前模块信息
        $model = '\app\common\model\\' . $this->modelName;
        $module = \app\common\model\Module::where('table_name', $this->tableName)->find();

        // 搜索
        if (Request::param('getList') == 1) {
            $where = MakeBuilder::getListWhere($this->tableName);
            $where[] = ['projects_id','=',Request::param('projectsId')];
            $orderByColumn = Request::param('orderByColumn') ?? $pk;
            $isAsc = Request::param('isAsc') ?? 'desc';
            return $model::getList($where, $this->pageSize, [$orderByColumn => $isAsc]);
        }
        // 检测单页模式
        $isSingle = MakeBuilder::checkSingle($this->modelName);
        if ($isSingle) {
            return redirect($isSingle);
        }
        // 构建页面
        return TableBuilder::getInstance()
            ->setDataUrl(Request::baseUrl() . '?getList=1&projectsId='.$projectsId)
            ->setUniqueId($pk)                              // 设置主键
            ->addColumns($coloumns)                         // 添加列表字段数据
            ->setSearch($search)                            // 添加头部搜索
            ->addTopButton('back',array('title'=>'返回项目列表','href'=>url('projects/index'),'class'=>'btn btn-primary'))
            ->addColumn('right_button', '操作', 'btn')      // 启用右侧操作列
            ->setAddUrl(url('add',array('projectsId'=>$projectsId)))
            ->addRightButtons($module->right_button)        // 设置右侧操作列
            ->addTopButtons($module->top_button)            // 设置顶部按钮组
            ->fetch();
    }

    // 添加
    public function add()
    {
        $projectsId = request()->get('projectsId');
        // 获取字段信息
        $coloumns = MakeBuilder::getAddColumns($this->tableName);
        // 获取分组后的字段信息
        $groups = MakeBuilder::getgetAddGroups($this->modelName, $this->tableName, $coloumns);
        // 构建页面
        $builder = FormBuilder::getInstance();
        
        $groups ? $builder->addGroup($groups) : $builder->addFormItems($coloumns);

        $extra_html = $this->extrahtml();
        $extra_script = $this->extrascript();
        $builder->addHtml($extra_html)->setExtraJs($extra_script)->addHidden('projects_id', $projectsId);
        
        return $builder->fetch();
    }

    public function extrahtml(){
        $html = '<div class="row dd_input_group " id="form_group_specs_type">
                    <div class="form-group">
                        <label class="col-xs-4 col-sm-2 col-md-2 col-lg-1 control-label dd_input_l" for="goods_specs_type">规格</label>
                        <div class="col-xs-7 col-sm-6 col-md-4 col-lg-4" id="showspecs">
                            <div class="dd_radio_lable_left">
                             <div class="btn btn-success btn-xs add-spec" style="margin:5px">添加规格</div>
                                <div class="control-group choose_config spec-more" style="padding-left: 20px;">
                                    <div class="skus-warp ">

                                    </div>
                                    <div class="clear"></div>
                                    <div id="skuTable">
                                        <table class="skuTable">
                                            <tbody>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                               
                             </div>
                        </div>
                        <div class="col-xs-1 col-sm-4 col-md-6 col-lg-6 dd_ts">*</div>
                    </div>
                </div>';
        return $html;
    }

    public function extrascript(){
        $html = <<<EOF
<script src="/static/admin/js/createSkuTable.js" type="text/javascript"></script>
<script type="text/javascript">
 $(function () {
    $('.add-spec').click(function () {
        $.modal.open('添加规格', 'addspec', '600', '400', callback);
    })
    $('body').on('click', '.deleteitem', function () {
         $(this).parent().parent().parent().remove();
    })
    $('body').on('click', '#skustart', function () {
        let arrJson = []
        let alreadySetSkuVals = [];
        $("tr[class*='sku_table_tr']").each(function (i, item) {
            let newObj = {}
            var skuPrice = $(this).find("input[type='text'][class*='setting_sku_price']").val() || 0;
            let propvalids = $(this).attr('propvalids');
            let propvalnames = $(this).attr('propvalnames');

            let names = propvalnames.split(';')
            newObj = {propvalids, skuPrice,propvalnames}
            alreadySetSkuVals.push(newObj)
        });

        var listhtml = '<ul class="specbor">';
        alreadySetSkuVals.forEach(function (item) {
            listhtml += '<li><label class="dd_radio_lable"><input type="checkbox" name="skulist[]" checked class="sku_value dn"  value="'+ item.propvalids + "|" + item.skuPrice +'"/>'+ item.propvalnames+ "-----"+ item.skuPrice +'元</label></li>';
        })
        listhtml += '</ul>';
  
        $('#showspecs').html(listhtml);


    })
})
function callback(index,b) {
    var body=layer.getChildFrame('body',index);
    var specid = body.contents().find('#specid').val();
    var specname = body.contents().find('#specname').val();
    if(specid){
        $.ajax({
            url: 'addspec',
            type: 'POST',
            data:{'id':specid},
            success:function(result){
                var html =  $('.skus-warp').html();
                html += '<div class="clear"><ul class="SKU_TYPE"><li is_required="1" propid="'+specid+'" sku-type-name="'+specname+'">'+specname+'：</li></ul><ul>';
                result.data.forEach(function (item) {
                    html += '<li><label class="dd_radio_lable"><input type="checkbox" class="sku_value dd_radio" propvalid="'+ item.id +'"  value="'+ item.name+'"/>'+ item.name+'</label></li>';
                })
                //html += '<li><a href="javascript:;" class="btn btn-danger btn-sm deleteitem">移除</a></li>';
                html += '</ul></div>';
                
                $('.skus-warp').html(html);
                parent.layer.close(index);
            } 
        })
    }else{
        $.modal.alertWarning('请选择左侧规格名称或添加对应规格的属性');
        return;
    }
}
</script>
EOF;
return $html;
    }

    public function addspec(){
        if (Request::isPost()) {
            $id = request()->post('id/d');
            $list = Db::name('specs_value')->where('specs_id',$id)->select();
            $this->result($list,1,'success');
        }else{
            $spec = config('spece');
            return view('addspec',['spec'=>$spec]);
        }
    }

    public function add_specs_value(){
        if (Request::isPost()) {
            $data['specs_id'] = request()->post('id/d');
            $data['name'] = request()->post('name/s');
            if($data['name'] == ''){
                $this->result('',0,'属性名称不能为空');
            }
            $dataid =  Db::name('specs_value')->where('specs_id',$data['specs_id'])->where('name',$data['name'])->value('id');
            if($dataid){
                 $this->result('',0,'已经存在属性'.$data['name']);
            }

            $id = Db::name('specs_value')->insertGetId($data);
            if($id){
                $list = Db::name('specs_value')->where('specs_id',$data['specs_id'])->select();
                $this->result($list,1,'添加成功');
            }else{
                $this->result('',0,'添加失败');
            }
            
        }else{
             $this->result('',0,'非法请求');
        }
    }

    public function delete_specs_value(){
       if (Request::isPost()) {
            $id = request()->post('id/d');
            $dataid =  Db::name('specs_value')->where('id',$id)->value('specs_id');
            if(!$dataid){
                 $this->result('',0,'该属性已删除');
            }

            $res = Db::name('projects_sku')->whereFindInSet('specs_value_id',$id)->select();
            if($res){
                $this->result('',0,'该属性有关联属性 无法删除');
            }

            Db::name('specs_value')->where('id',$id)->delete();

            $list = Db::name('specs_value')->where('specs_id',$dataid)->select();
            $this->result($list,1,'删除成功');
        
            
        }else{
             $this->result('',0,'非法请求');
        }
    }

 
    // 添加保存
    public function addPost()
    {
        if (Request::isPost()) {
            $data = request()->post();

            $result = $this->validate($data, $this->validate);
            if (true !== $result) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                $model = '\app\common\model\\' . $this->modelName;
                foreach ($data['skulist'] as $value) {
                    $value = explode('|', $value);
                    $dataitem['specs_value_id'] = $value[0];
                    $dataitem['price'] = $value[1];
                    $dataitem['status'] = $data['status'];
                    $dataitem['sort'] = $data['sort'];
                    $dataitem['projects_id'] = $data['projects_id'];
                    $res = $model::where('projects_id',$data['projects_id'])->where('specs_value_id',$value[0])->value('id');
                    if(!$res){
                        $result = $model::addPost($dataitem); 
                    }else{
                        $this->error('添加失败，该项目下存在相同的sku');
                    }
                    
                }
                if ($result['error']) {
                    $this->error($result['msg']);
                } else {
                    $this->success($result['msg'], 'index?projectsId='.$data['projects_id']);
                }
            }
        }
    }

    // 修改
    public function edit(string $id)
    {
        $model = '\app\common\model\\' . $this->modelName;
        $info = $model::edit($id)->toArray();
        // 获取字段信息
        $coloumns = MakeBuilder::getAddColumns($this->tableName, $info);
        // 获取分组后的字段信息
        $groups = MakeBuilder::getgetAddGroups($this->modelName, $this->tableName, $coloumns);

        // 构建页面
        $builder = FormBuilder::getInstance();
        $groups ? $builder->addGroup($groups) : $builder->addFormItems($coloumns);
        return $builder->fetch();
    }

    // 修改保存
    public function editPost()
    {
        if (Request::isPost()) {
            $data = MakeBuilder::changeFormData(Request::except(['file'], 'post'), $this->tableName);
            $result = $this->validate($data, $this->validate);
            if (true !== $result) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                $model = '\app\common\model\\' . $this->modelName;
                $result = $model::editPost($data);
                if ($result['error']) {
                    $this->error($result['msg']);
                } else {
                    $this->success($result['msg'], 'index');
                }
            }
        }
    }

    // 删除
    public function del(string $id)
    {
        if (Request::isPost()) {
            if (strpos($id, ',') !== false) {
                return $this->selectDel($id);
            }
            $model = '\app\common\model\\' . $this->modelName;
            return $model::del($id);
        }
    }

    // 批量删除
    public function selectDel(string $id){
        if (Request::isPost()) {
            $model = '\app\common\model\\' . $this->modelName;
            return $model::selectDel($id);
        }
    }

    // 排序
    public function sort()
    {
        if (Request::isPost()) {
            $data = Request::post();
            $model = '\app\common\model\\' . $this->modelName;
            return $model::sort($data);
        }
    }

    // 状态变更
    public function state(string $id)
    {
        if (Request::isPost()) {
            $model = '\app\common\model\\' . $this->modelName;
            return $model::state($id);
        }
    }

    // 导出
    public function export()
    {
        \app\common\model\Base::export($this->tableName, $this->modelName);
    }

}
